//
//  MyProfit_V2.swift
//  LeGou
//
//  Created by lxm on 2022/10/9.
//

import UIKit

class MyProfit_V2: ZMViewController {

    //MARK:--------------------属性--------------------
    var data = ZMUtil.fastNilBehavior(type: MineModels.ProfitData.self)

    var type = 1

    var myProfitInfo = ZMUtil.fastNilBehavior(type: MineModels.Profit.self)
    
    let walletInfo = ZMUtil.fastNilBehavior(type: MineModels.WalletInfo.self)

    //MARK:--------------------UI控件--------------------
    @IBOutlet weak var bottomContent: UIView!
    
    @IBOutlet weak var indexContent: UIView!
    
    @IBOutlet weak var topView: UIView!
    
    @IBOutlet weak var drawLabel: UILabel!
    
    @IBOutlet weak var money: UILabel!
    
    let loading = XMLoadingView()
    
    var seg : XMIndexHeaderView!
    
    let pro = MyProfitTabel().then { v in
        v.layer.cornerRadius = 12
        v.backgroundColor = .white
    }
    
    let tips = ZMUtil.label(title: "温馨提示：\n1、会员每月需要消费9笔或者完成9个悬赏任务，共富收益和合伙人收益都可变为可用；\n2、未完成任务，次月1号共富收益将清0；", color: "#666666".zm.hex(), font: UIFont.systemFont(ofSize: 14)).then({$0.numberOfLines = 0})

    let taskButton = ZMUtil.button(title: "立即做任务", font: UIFont.systemFont(ofSize: 16), color: .white).then({$0.backgroundColor = Style.mainColor;$0.layer.cornerRadius=23})
    
    //MARK:--------------------生命周期--------------------
    override func viewDidLoad() {
        super.viewDidLoad()
        setUI()
        addConstraints()
        bindAction()
        loadDate()
        _ = xmIndexHeaderViewShouldScroll(to: 0, indexView: seg)
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        loadWallet()
    }
    
    //MARK:--------------------UI--------------------
    func setUI() {
        title = "我的收益"
        
        //seg
        let config  = XMIndexHeaerViewConfig()
        config.font = UIFont.systemFont(ofSize: 14, weight: .regular)
        config.fontColor  = UIColor.zm.color666666()
        config.selectFont = UIFont.systemFont(ofSize: 18, weight: .medium)
        config.selectFontColr = Style.mainColor
        config.lineViewCornerRadius = 1.5
        
        seg = XMIndexHeaderView(frame: CGRect(x: 0, y: 0, width: SCREEN_W, height: 44), withTitleArray:["今日明细", "本周明细", "本月明细"], animation: false, delegate: self)!
        seg.lineColor = Style.mainColor
        seg.lineWidth = 17
        seg.config = config
        seg.backGroundColor = .clear
                
        indexContent.addSubview(seg)
        
        bottomContent.addSubview(pro)

        bottomContent.addSubview(tips)
        
        bottomContent.addSubview(taskButton)

        
        setRightCustomBtn(titleStr: "账单明细", color: UIColor.zm.color333333(), font: UIFont.systemFont(ofSize: 14))

    }
    
    func addConstraints() {
        pro.snp.makeConstraints { make in
            make.top.equalTo(indexContent.snp.bottom).offset(0)
            make.left.equalToSuperview().offset(16)
            make.right.equalToSuperview().offset(-16)
        }
        
        tips.snp.makeConstraints { make in
            make.top.equalTo(pro.snp.bottom).offset(16)
            make.left.equalToSuperview().offset(16)
            make.right.equalToSuperview().offset(-16)
        }
        
        taskButton.snp.makeConstraints { make in
            make.top.equalTo(tips.snp.bottom).offset(48)
            make.left.equalToSuperview().offset(16)
            make.right.equalToSuperview().offset(-16)
            make.height.equalTo(46)
            make.bottom.equalToSuperview().offset(-82)
        }
    }
    
    override func viewWillLayoutSubviews() {
        super.viewWillLayoutSubviews()
        bottomContent.style.Gradient(colors: ["#F3BAB2".zm.hex().cgColor,
                                              "#FFFFFF".zm.hex().cgColor], locations: [0, 0.89], startPoint: CGPoint(x: 0.5, y: 0), endPoint: CGPoint(x: 0.5, y: 1))
        
        ZMUtil.clipCircle(view: topView, Corner: [.topLeft, .topRight], radius: 12)
        
        ZMUtil.clipCircle(view: bottomContent, Corner: [.topLeft, .topRight], radius: 12)

    }
    
    //MARK:--------------------methods--------------------
    func bindAction() {
        taskButton.rx.tap.subscribe(onNext:{ [unowned self] resp in
            let v = ZMUtil.loadNibViewFullScreen(nibName: DoTaskView.self)
            APPWindow?.addSubview(v)
//            router.push("xm://main/Mine/invite")
        }).disposed(by: disposeBag)
        
        self.data.subscribe(onNext:{ [unowned self] resp in
            let titlesMap = [
                1 : "自购收益",
                2 : "推荐收益",
                3 : "共富收益",
                4 : "合伙人收益",
                5 : "消费奖池分红",
                6 : "红包收益",
                7 : "竞购收益",
                8 : "竞购收益(自)"
            ]
            if let resp = resp {
                let temp = resp.incomeDataResponseList.sorted(by: {$0.type < $1.type})
                var tData = [[String]]()
                let bh = ZMUtil.DecimalNumberHandler(roundingMode: .down, scale: 2)
                for t in temp {
                    guard let title = titlesMap[t.type] else {continue}
                    let item = t
                        var flag = "0"
                        flag = item.taskStatus == 1 ? "0" : "1"
                        if item.type == 6 || item.type == 7 || item.type == 8 {
                            tData.append([title, "-", "-", "¥\(NSDecimalNumber.init(string: item.settleMoney).rounding(accordingToBehavior: bh))", flag, "\(item.type)"])
                        } else {
                            tData.append([title, "\(item.quantity)", "¥\(NSDecimalNumber.init(string: item.estimateMoney).rounding(accordingToBehavior: bh))", "¥\(NSDecimalNumber.init(string: item.settleMoney).rounding(accordingToBehavior: bh))", flag, "\(item.type)"])
                        }
                }
                self.pro.data = tData
            }
        }).disposed(by: disposeBag)
        
        pro.onClick = { [weak self] i in
            guard let self = self, let type = ProfitIndexType.init(rawValue: Int(i[5]) ?? 0)  else {return}
            if type == .pool {
                let vc = ProfitList()
                vc.type = type
                vc.title = "消费奖池分红"
                self.navigationController?.pushViewController(vc, animated: true)
            } else if type == .redBag {
                let vc = RedBagProfitList()
                vc.type = type
                self.navigationController?.pushViewController(vc, animated: true)
            } else if type == .auction || type == .hammer {
                let vc = ProfitList()
                vc.status = .all
                vc.type = type
                self.navigationController?.pushViewController(vc, animated: true)
            } else {
                let vc = ProfitIndex()
                vc.type = type
                self.navigationController?.pushViewController(vc, animated: true)
            }
        }
        
        self.myProfitInfo.subscribe(onNext:{ [unowned self] resp in
            if let resp = resp {
                self.money.text = resp.nowMoney.zm.toString(keep: 4)
            } else {
                self.money.text = "0"
            }
        }).disposed(by: disposeBag)
        
        self.walletInfo.subscribe(onNext:{ [unowned self] resp in
            if let resp = resp {
                self.drawLabel.text = resp.withdrawalDate
                self.tips.text = resp.tips
            } else {
                self.drawLabel.text = ""
            }
        }).disposed(by: disposeBag)
    }
    
    override func rightBtnClick(sender: UIButton) {
        router.push("xm://main/Mine/trade_detail", context: ["type" : 1])
    }

    func loadWallet() {
        MineAPI.myProfit.rxRequest(type: MineModels.Profit.self).subscribe(onNext:{ [unowned self] resp in
            self.myProfitInfo.accept(resp)
        }).disposed(by: disposeBag)
    }
    
    // 转账
    @IBAction func onTrans(_ sender: Any) {
        router.push("xm://main/Mine/TransferPage", context: ["type" : 1])
    }
    
    // 提现
    @IBAction func onWithdraw(_ sender: Any) {
        if !LoginService.shared.checkLogin() {return}
        
        if !LoginService.shared.checkRealName() {return}
        
        router.push("xm://main/Mine/withdraw", context: ["type" : 1])
    }
    
    func loadDate() {
        let api = MineAPI.walletInfo([:])
        api.rxRequest(type: MineModels.WalletInfo.self).subscribe(onNext:{ [unowned self] resp in
            self.walletInfo.accept(resp)
        }, onError: { e in
        }).disposed(by: disposeBag)
    }
    //MARK:--------------------delegate--------------------

}

extension MyProfit_V2 : XMIndexHeaderViewDelegate {
    func xmIndexHeaderViewDidselected(with index: Int) {
        
    }
    
    func xmIndexHeaderViewShouldScroll(to index: Int, indexView indexheaderView: XMIndexHeaderView!) -> Bool {
        ZMToast.showActivity()
        MineAPI.myProfitData(["type" : index + 1]).rxRequest(type: MineModels.ProfitData.self).subscribe(onNext:{ [unowned self] resp in
            ZMToast.hiddenActivity()
            self.data.accept(resp)
            self.type = index + 1
            self.seg.lineViewScrolle(to: index, animation: true)
        }, onError: { _ in

        }).disposed(by: disposeBag)
        return false;
    }
}
